package edu.msg.jthr.backend.model;

import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;

@MappedSuperclass
public abstract class AbstractModel {

	@Column(name = "Uuid")
	private String uuid;

	public AbstractModel() {
	}

	public AbstractModel(String uuid) {
		this.uuid = uuid;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((this.getUUID() == null) ? 0 : uuid.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AbstractModel other = (AbstractModel) obj;
		if (this.getUUID() == null) {
			if (other.uuid != null)
				return false;
		} else if (!this.getUUID().equals(other.uuid))
			return false;
		return true;
	}

	public String getUUID() {
		return ensureUuid();
	}

	@PrePersist
	public String ensureUuid() {
		if (uuid == null) {
			uuid = UUID.randomUUID().toString();
		}
		return uuid;
	}

}
